<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <label class="el-form-item-label">订单编号</label>
        <el-input v-model="query.orderNo" clearable placeholder="订单编号" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />

        <label class="el-form-item-label">订单状态</label>
        <el-select
          v-model="query.orderStatus"
          clearable
          size="small"
          placeholder="状态"
          class="filter-item"
          style="width: 130px"
          @change="crud.toQuery"
        >
          <el-option
            v-for="item in dict.order_status"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <label class="el-form-item-label">收货人姓名</label>
        <el-input v-model="query.receiveName" clearable placeholder="收货人姓名" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <label class="el-form-item-label">收货人电话</label>
        <el-input v-model="query.receivePhone" clearable placeholder="收货人电话" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <rrOperation :crud="crud" />
      </div>

      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog
        :close-on-click-modal="false"
        :before-close="crud.cancelCU"
        :visible.sync="crud.status.cu > 0"
        :title="crud.status.title"
        width="800px"
      >
        <el-form ref="form" :model="form" :rules="rules" :inline="true" size="small" label-width="120px">
          <!--          <el-form-item label="订单编号">-->
          <!--            <el-input v-model="form.orderNo" style="width: 370px;"/>-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="订单名称" prop="orderName">-->
          <!--            <el-input v-model.trim="form.orderName" :maxlength="25" style="width: 240px;" :disabled="crud.status.add ===0?true:false" />-->
          <!--          </el-form-item>-->
          <el-form-item label="订单类型">
            <el-select v-model="form.orderType" :disabled="crud.status.add ===0?true:false" filterable placeholder="请选择" style="width: 240px;">
              <el-option
                v-for="item in dict.order_type"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item
            label="收货人姓名"
            prop="receiveName"
          >
            <el-input v-model.trim="form.receiveName" :maxlength="25" style="width: 240px;" />
          </el-form-item>
          <el-form-item
            label="收货人电话"
            prop="receivePhone"
          >
            <el-input v-model.trim="form.receivePhone" style="width: 240px;" />
          </el-form-item>
          <el-form-item
            label="收货地址"
            prop="receiveAddress"
          >
            <el-input v-model.trim="form.receiveAddress" :maxlength="25" style="width: 240px;" />
          </el-form-item>
          <!--
          <el-form-item label="订单状态">
            <el-select v-model="form.orderStatus" filterable placeholder="请选择">
              <el-option
                v-for="item in dict.order_status"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>-->
          <el-form-item
            label="学习卡类型"
            prop="cardType"
          >
            <el-select v-model="form.cardType" :disabled="crud.status.add ===0?true:false" filterable placeholder="请选择" style="width: 240px;">
              <el-option
                v-for="item in dict.card_type"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="学习卡数量(张)"
            prop="cardCount"
          >
            <el-input-number v-model="form.cardCount" :disabled="crud.status.add ===0?true:false" style="width: 240px;" :controls="false" :min="1" />
          </el-form-item>
          <el-form-item
            label="单价(元)"
            prop="cardAmount"
          >
            <el-input-number v-model="form.cardAmount" :disabled="crud.status.add ===0?true:false" style="width: 240px;" :controls="false" :min="1" />
          </el-form-item>
          <el-form-item
            label="付款总额(元)"
            prop="totalAmount"
          >
            <el-input v-model="form.totalAmount" :disabled="crud.status.add ===0?true:false" style="width: 240px;" :value="sum" readonly />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        :data="crud.data"
        size="small"
        style="width: 100%;"
        @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="orderNo" label="订单编号" />
        <!-- <el-table-column prop="customerPhone" label="客户电话" width="95" align="center" /> -->
        <el-table-column prop="receiveName" label="收货人姓名" align="center" />
        <el-table-column prop="receivePhone" label="收货人电话" width="95" align="center" />
        <!--
        <el-table-column prop="orderName" label="订单名称" />
        <el-table-column prop="orderType" label="订单类型">
          <template slot-scope="scope">
            {{ dict.label.order_type[scope.row.orderType] }}
          </template>
        </el-table-column>
        <el-table-column prop="customerId" label="客户编号" />

        <el-table-column prop="receiveAddress" label="收件人地址" />
        -->
        <el-table-column prop="orderStatus" label="订单状态" align="center">
          <template slot-scope="scope">
            {{ dict.label.order_status[scope.row.orderStatus] }}
          </template>
        </el-table-column>
        <el-table-column prop="cardType" label="学习卡类型" align="center">
          <template slot-scope="scope">
            {{ dict.label.card_type[scope.row.cardType] }}
          </template>
        </el-table-column>
        <el-table-column prop="cardCount" label="学习卡数量(张)" align="center" />
        <el-table-column prop="cardAmount" label="单价(元)" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.cardAmount /100 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="总额(元)" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.totalAmount /100 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="customerName" label="下单人姓名" align="center" />
        <el-table-column prop="createTime" label="下单时间" align="center">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column v-permission="['admin','order:edit','order:del']" label="操作" width="250px" align="center">
          <template slot-scope="scope">
            <div style="float: right; padding: 3px 0px">
              <el-button
                type="warning"
                :disabled="scope.row.orderType==1 && scope.row.orderStatus == 0 && Number(scope.row.customerId) === user.id?false:true"
                @click.stop="topUp(scope.row)"
              >付款</el-button>
              <!-- 订单状态:0新增-->
              <el-button
                type="danger"
                :disabled="scope.row.orderStatus == 0 && Number(scope.row.customerId) === user.id?false:true"
                @click="cancelOrder(scope.row)"
              >取消订单</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <order-pay :show-top-up="showTopUp" :data-list="payInfo" @close="topUpClose" />
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudOrder from '@/api/order/order'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import pagination from '@crud/Pagination'
import { isvalidPhone } from '@/utils/validate'
import orderPay from '../components/orderPay'
import { cancel } from '@/api/card/order'

const defaultForm = {
  orderNo: null,
  orderName: null,
  orderType: 0,
  customerId: null,
  customerName: null,
  customerPhone: null,
  receiveName: null,
  receivePhone: null,
  receiveAddress: null,
  orderStatus: 0,
  cardType: 1,
  cardCount: 1,
  cardAmount: 1,
  totalAmount: 1,
  createTime: null,
  payMethod: '4',
  remark: null
}
export default {
  name: 'Order',
  components: { pagination, crudOperation, rrOperation, orderPay },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['order_type', 'order_status', 'card_type', 'pay_method'],
  cruds() {
    return CRUD({ title: '订单', url: 'api/order', idField: 'orderNo', sort: 'orderNo,desc', crudMethod: { ...crudOrder },
      optShow: {
        add: true,
        edit: true,
        del: false,
        download: true,
        reset: true
      }
    })
  },
  data() {
    const validPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入电话'))
      } else if (!isvalidPhone(value)) {
        callback(new Error('请输入正确的11位电话号码'))
      } else {
        callback()
      }
    }
    return {
      showTopUp: false,
      editStatus: false,
      payDataList: {
        totalAmount: '',
        orderNo: ''
      },
      permission: {
        add: ['admin', 'order:add'],
        edit: ['admin', 'order:edit'],
        del: ['admin', 'order:del']
      },
      rules: {
        orderNo: [
          { required: true, message: '订单编号不能为空', trigger: 'blur' }
        ],
        // orderName: [
        //   { required: true, message: '订单名称不能为空', trigger: 'blur' }
        // ],
        orderType: [
          { required: true, message: '订单类型不能为空', trigger: 'blur' }
        ],
        receiveName: [
          { required: true, message: '收货人不能为空', trigger: 'blur' }
        ],
        receivePhone: [
          { required: true, trigger: 'blur', validator: validPhone }
        ],
        receiveAddress: [
          { required: true, message: '收货地址不能为空', trigger: 'blur' }
        ],
        cardType: [
          { required: true, message: '学习卡类型不能为空', trigger: 'blur' }
        ],
        cardCount: [
          { required: true, message: '学习卡数量不能为空', trigger: 'blur' }
        ],
        cardAmount: [
          { required: true, message: '单价不能为空', trigger: 'blur' }
        ],
        totalAmount: [
          { required: true, message: '付款总额不能为空', trigger: 'blur' }
        ]
      },
      user: null,
      cardAmount: 1,
      cardAcount: 1,
      total: 0
    }
  },
  computed: {
    sum: function() {
      return this.form.cardCount * this.form.cardAmount
    },
    payInfo: function() {
      return {
        customerId: this.user.phone,
        totalMoney: this.payDataList.totalAmount, // 订单金额
        orderNo: this.payDataList.orderNo // 订单编号
      }
    }
  },
  watch: {
    sum: {
      deep: true,
      handler: function(newVal) {
        this.form.totalAmount = this.form.cardAmount * this.form.cardCount
        // this.total = this.form.cardAmount * this.form.cardCount
      }
    }
  },
  created() {
    // 获取用户信息
    this.user = this.$store.getters.user
  },
  methods: {
    topUp(value) {
      this.payDataList = value
      this.showTopUp = true
    },
    topUpClose(v) {
      this.showTopUp = false
      if (v) {
        // 刷新数据
        this.crud.toQuery()
      }
    },
    cancelOrder(param) {
      const user = this.$store.getters.user
      const params = param
      params.buyId = user.id
      params.buyName = user.username
      params.buyPhone = user.phone
      cancel(params).then(res => {
        this.$alert('取消订单成功', '提示', {
          confirmButtonText: '确定',
          callback: action => {
            this.crud.toQuery()
          }
        })
      })
    },
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    [CRUD.HOOK.afterToCU](crud, form) {
      form.orderType = form.orderType.toString()
      form.orderStatus = form.orderStatus.toString()
      form.cardType = form.cardType.toString()
    },

    [CRUD.HOOK.beforeToCU](crud, form) {
      // 用户信息
      form.customerId = this.user.id
      form.customerName = this.user.username
      form.customerPhone = this.user.phone
      // alert(form.customerName)
    },
    [CRUD.HOOK.beforeToEdit](a, b) {
      // 订单状态只有新建状态下才能进行编辑
      if (b.orderStatus !== 0) {
        this.$message.error('订单状态只有新建状态下才能进行编辑')
        return false
      }
      b.cardAmount = b.cardAmount / 100
      return true
    },

    [CRUD.HOOK.afterToEdit](crud) {
      this.editStatus = true
    },
    // 提交前
    [CRUD.HOOK.beforeSubmit](crud) {
      if (this.editStatus) {
        this.form.cardAmount = this.form.cardAmount * 100
        this.form.totalAmount = this.form.totalAmount * 100
      }
    }
  }
}
</script>

<style scoped lang="scss">
  .head-container {
    ::v-deep .el-input-number.is-without-controls .el-input__inner {
      text-align: left;
    }

    /** 去除input输入框样式 */
    ::v-deep  input[type=number]::-webkit-inner-spin-button {
      -webkit-appearance: none;
    }
	::v-deep input[type="number"]{
	    -moz-appearance:textfield;
	}
  }
</style>
